import { createContext, useReducer, useContext } from 'react'
import { Appearance } from 'react-native'

const initialData = {
  user: {
    userName: 'hello',
    birth: '1996-12-1'
  },
  theme: 'light'
}

export const AppDataContext = createContext(initialData)
export const AppDataDispatchContext = createContext((val: any) => val)

export function AppDataProvider({ children }) {
  const [appData, dispatch] = useReducer(appDataReducer, initialData)
  return (
    <AppDataContext.Provider value={appData}>
      <AppDataDispatchContext.Provider value={dispatch}>
        {children}
      </AppDataDispatchContext.Provider>
    </AppDataContext.Provider>
  )
}

export const useAppData = () => {
  return useContext(AppDataContext)
}

export const useAppDataDispatch = () => {
  return useContext(AppDataDispatchContext)
}

const appDataReducer = (appData, action) => {
  switch(action.type) {
    case 'changeTheme':
      Appearance.setColorScheme(action.value)
      return { ...appData, theme: action.value }
  }
}
